//
//  OrderVC.m
//  UHealth
//
//  Created by hanyou on 15/3/18.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "OrderVC.h"
#import "NavView.h"
#import "MJRefresh.h"
#import "iToast.h"
#import "AFNetworking.h"
#import "orderCell.h"
#import "OrderInfoVC.h"

@interface OrderVC ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong)  UITableView        *contentTableView;
@property (nonatomic, strong)  NSMutableArray     *dataArray;
@property (nonatomic        )  int                page;


@end

@implementation OrderVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"myOrder") andVC:self];
    [self.view addSubview:nav];
    
    UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"none"]];
    img.frame = CGRectMake(130, 200 ,WIDTH-260, WIDTH-260);
    img.center = self.view.center;
    
    
    _dataArray = [NSMutableArray array];
    
    _contentTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, WIDTH, HEIGHT - kNavHeight) style:UITableViewStyleGrouped];
    _contentTableView.delegate = self;
    _contentTableView.dataSource = self;
    _page = 1;
    
    
    //下拉刷新订单信息
    __unsafe_unretained typeof(self) vc = self;
    [_contentTableView addHeaderWithCallback:^{
        if (!kNetID) {//测试ID
            [[iToast makeText:kLocal(@"notLogin")] show];
            [vc.contentTableView headerEndRefreshing];
            return ;
        }
        
        if (!kNetIsOK) {
            [[iToast makeText:kLocal(@"netNoOk")] show];
            [vc.contentTableView headerEndRefreshing];
            return ;
        }
        
        vc.page = 1;
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp",kBaseUrl];
        NSDictionary *parameters = @{@"action": @"getmyshop",
                                     @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"pic":@"all",
                                     @"pages":[NSString stringWithFormat:@"%d",vc.page]};
        
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //kDebug(@"Success: %@", operation.responseString);
            [vc.dataArray removeAllObjects];
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            if(type){
                
                NSArray *arr =[responseObject objectForKey:@"myArr"];
                for (int i = 0; i< arr.count; i++) {
                    [vc.dataArray addObject:arr[i]];
                }
                if (vc.dataArray.count > 0) {
                    img.hidden = YES;
                }else{
                    img.hidden = NO;
                }
                vc.page ++;
                
            }else{
            }
            [vc.contentTableView reloadData];
            [vc.contentTableView headerEndRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
            [vc.contentTableView headerEndRefreshing];
        }];
        
    }];
    
    [_contentTableView headerBeginRefreshing];//开始刷新
    //底部加载更多
    [_contentTableView addFooterWithCallback:^{
        if (!kNetID) {//
            [[iToast makeText:kLocal(@"notLogin")] show];
            [vc.contentTableView footerEndRefreshing];
            return ;
        }
        if (!kNetIsOK) {
            [[iToast makeText:kLocal(@"netNoOk")] show];
            [vc.contentTableView footerEndRefreshing];
            return ;
        }
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp",kBaseUrl];
        NSDictionary *parameters = @{@"action": @"getmyshop",
                                     @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"pic":@"all",
                                     @"pages":[NSString stringWithFormat:@"%d",vc.page]};
        
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //kDebug(@"Success: %@", operation.responseString);
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            NSString *str = responseObject[@"msg"];
            if(type){
                
                if (vc.page <=[responseObject[@"pagesize"]intValue]) {
                    NSArray *arr =responseObject[@"myArr"];
                    for (int i = 0; i< arr.count; i++) {
                        [vc.dataArray addObject:arr[i]];
                    }
                    if (vc.dataArray.count > 0) {
                        img.hidden = YES;
                    }else{
                        img.hidden = NO;
                    }
                    [vc.contentTableView reloadData];
                    
                }else{
                    str = kLocal(@"no_other_order");
                }
                vc.page ++;
            }else{
            }
            [[iToast makeText:str] show];
            [vc.contentTableView footerEndRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
            [vc.contentTableView footerEndRefreshing];
        }];
        
    }];
    
    [self.view addSubview:_contentTableView];
    
    
    
    [_contentTableView registerNib:[UINib nibWithNibName:NSStringFromClass([orderCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([orderCell class])];
    
    [self.view addSubview:img];


    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    orderCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([orderCell class]) forIndexPath:indexPath];
    [cell setData:_dataArray[indexPath.section]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (/* DISABLES CODE */ (YES)) {
        OrderInfoVC *or = [[OrderInfoVC alloc]initWithDic:_dataArray[indexPath.section]];
        [self presentViewController:or animated:YES completion:nil];
    }else{//取消订单
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp",kBaseUrl];
        NSDictionary *parameters = @{@"action": @"delorder",
                                     @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"orderid":_dataArray[indexPath.section][@"orderid"]};
        
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            kDebug(@"Success: %@", operation.responseString);
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            NSString *str = responseObject[@"msg"];
            if(type){
                
            }else{
            }
            [[iToast makeText:str] show];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
        }];
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
